package com.google.code.hibernate.rest;

import static com.google.code.hibernate.rest.internal.InternalPreconditions.checkNotNull;

import org.hibernate.SessionFactory;
import org.hibernate.classic.Session;

/**
 * 
 * @author wangzijian
 * 
 */
public class CurrentSession {

	private static final ThreadLocal<Session> CURRENT_SESSION = new ThreadLocal<Session>();
	
	private CurrentSession() {
		
	}
	
	public static Session of(SessionFactory sessionFactory) {
		checkNotNull(sessionFactory, "sessionFactory");
		Session session = CURRENT_SESSION.get();
		if (session != null) {
			return session;
		}
		session = sessionFactory.openSession();
		CURRENT_SESSION.set(session);
		return session;
	}
	
	public static void close() {
		Session session = CURRENT_SESSION.get();
		if (session != null) {
			CURRENT_SESSION.remove();
			session.close();
		}
	}
	
}
